import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from "../views/Index";
import store from "../store";
import axios from "../axios";


Vue.use(VueRouter)

const routes = [
    {
        path: '/login',
        name: 'Login',
        //采用懒加载的方式
        component: () => import("../views/Login")
    },
    {
        path: '/',
        name: 'Home',
        component: Home,
        children: [{
            path: '/index',
            name: 'Index',
            meta: {
                title: "首页"
            },
            component: Index
        }, {
            path: '/userCenter',
            name: 'UserCenter',
            meta: {
                title: "个人中心"
            },
            component: () => import('../views/UserCenter.vue')
        }]
    }]


const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {

    let hasRoute = store.state.menus.hasRoutes

    //获取浏览器中的LocalStorage中的token
    let token = localStorage.getItem("token")

    if (to.path == '/login') {
        next()

    } else if (!token) {
        next({path: '/login'})


    }
    //有token没路由时，获取导航栏信息
    else if (token && !hasRoute) {
        axios.get("/sys/menu/nav", {
            headers: {
                Authorization: localStorage.getItem("token")
            }
        }).then(res => {

            console.log(res.data.data)

            // 拿到menuList
            store.commit("setMenuList", res.data.data.nav)

            // 拿到用户权限
            store.commit("setPermList", res.data.data.authoritys)

            console.log("以下为menuList————————"+store.state.menus.menuList)

            // 动态绑定路由
            let newRoutes = router.options.routes

            res.data.data.nav.forEach(menu => {
                if (menu.children) {
                    menu.children.forEach(e => {

                        // 转成路由
                        let route = menuToRoute(e)

                        // 吧路由添加到路由管理中
                        if (route) {
                            newRoutes[1].children.push(route)
                        }

                    })
                }
            })

            console.log("newRoutes")
            console.log(newRoutes)
            router.addRoutes(newRoutes)

            hasRoute = true
            store.commit("changeRouteStatus", hasRoute)
        })
    }


    next()
})


// 导航转成路由
const menuToRoute = (menu) => {

    if (!menu.component) {
        return null
    }

    let route = {
        name: menu.name,
        path: menu.path,
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }
    route.component = () => import('../views/' + menu.component + '.vue')

    return route
}

export default router
